<?php

function languageEnabled($lang){
	if(in_array($lang, explode(",", LANGUAGES))){
		return true;
	}
	return false;
}

function includeLanguage($language){
	global $LANGUAGES;
	if(!isset($LANGUAGES[$language])){
		$LANGUAGES[$language] = include(PATHROOT . "language/" . $language . ".php");
 	}
 	return $LANGUAGES[$language];
}

function setLanguage($lang){
	global $currentLang;
	global $LANG;
	if(languageEnabled($lang)){
		$currentLang = $lang;
		$LANG = includeLanguage($lang);
	}else{
		$LANG = includeLanguage(DEFAULTLANG);
	}
}

function langEcho($string, $language = '', $lower = false){
	GLOBAL $LANG;
	GLOBAL $DEFAULTLANG;
	$langToUse = $LANG;
	if ($language && ($language != getLanguage()) && languageEnabled($language)) {
		$langToUse = includeLanguage($language);
	}
	$key = $string;
	if($lower){
		$key = strtolower($string);
	}
	if($langToUse && array_key_exists($key, $langToUse)){
		return  $langToUse[$key];
 	}

	return $string;
}

function getLanguage(){
	global $currentLang;

	if(isset($currentLang) && languageEnabled($currentLang)){
		return $currentLang;
	}

	if(isUserLoggedIn()){
		return $_SESSION["userlang"];
	}

	if(isset($_COOKIE['lang'])){
		return $_COOKIE['lang'];
	}

	return DEFAULTLANG;
}

function ParseDateTimeToEn($date){
	$size = strlen($date);
	$day = "";
	$month = "";
	$year = "";
	if (getLanguage() == "en"){
		return $date;
	}else if (getLanguage() == "pt" || getLanguage() == "es"){
		for($i = 0; $i<2; $i++){
			$day.= $date[$i];
		}
		for($i = 3; $i<5; $i++){
			$month.= $date[$i];
		}
		for($i = 6; $i<$size; $i++){
			$year.= $date[$i];
		}
	}

	return $month . "/" . $day . "/" . $year;
}

function ParseDateTimeToEs($date){
	$size = strlen($date);
	$day = "";
	$month = "";
	$year = "";

	for($i = 0; $i<2; $i++){
		$month.= $date[$i];
	}
	for($i = 3; $i<5; $i++){
		$day.= $date[$i];
	}
	for($i = 6; $i<$size; $i++){
		$year.= $date[$i];
	}


	return $day . "/" . $month . "/" . $year;
}
function getLanguageFromNamespace($namespace) {
    GLOBAL $LANG;
    $return = array();
    $pattern = '/^' . $namespace.'/';
    foreach( $LANG as $key => $word) {
        if(preg_match($pattern, $key)) {
            $key = str_replace($namespace, "", $key);
            $return [$key] = $word;
        }
    }
    return $return;
}


?>